package com.aaa;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private AlertDialog goSettingDialog;
    private TextView text1;

    private static final int PERMISSION_REQUEST_CODE = 200;
    private static final int ALL_FILES_ACCESS_REQUEST_CODE = 201;

    private static final long PERMISSION_CHECK_INTERVAL = TimeUnit.SECONDS.toMillis(10);

    private CountDownTimer permissionCheckTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            checkAndRequestAllFilePermission();
        } else {
            requestPermission();
        }
        startPermissionCheckTimer();
    }


    private void startPermissionCheckTimer() {
        permissionCheckTimer = new CountDownTimer(Long.MAX_VALUE, PERMISSION_CHECK_INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (Environment.isExternalStorageManager()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateUI();
                            }
                        });
                    }
                } else {
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            == PackageManager.PERMISSION_GRANTED) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateUI();
                            }
                        });
                    }
                }
            }

            @Override
            public void onFinish() {
            }
        };
        permissionCheckTimer.start();
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    private void checkAndRequestAllFilePermission() {
        if (!Environment.isExternalStorageManager()) {
            showGoSettingDialog();
        } else {
            updateUI();
        }
    }

    private void showGoSettingDialog() {
        if (goSettingDialog == null) {
            goSettingDialog = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("Please allow it to access all your files")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivityForResult(intent, ALL_FILES_ACCESS_REQUEST_CODE);
                        }
                    }).create();
        }
        goSettingDialog.show();
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                updateUI();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ALL_FILES_ACCESS_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager()) {
                updateUI();
            }
        }
    }

    private void updateUI() {
        if (text1 == null) {
            text1 = findViewById(R.id.text1);
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 100; i++) {
            sb.append(i);
            if (i != 100) {
                sb.append(", ");
            }
        }
        text1.setText(sb.toString());
        Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, BActivity.class);
                intent.putExtra("number", sb.toString());
                startActivity(intent);
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (permissionCheckTimer != null) {
            permissionCheckTimer.cancel();
            permissionCheckTimer = null;
        }
    }
}
